import axios from "axios"
import { useUserStore } from "@/store/modules/user"
import router from "@/router"
import { ElMessage } from "element-plus"

const request = axios.create({
  baseURL: "/admin",
  timeout: 5000
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = useUserStore().token
    if (token) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const data = res.data
    return data
  },
  (error) => {
    console.dir(error) // for debug
    if (error.response.status === 401) {
      useUserStore().logout()
      ElMessage.warning("登录信息已过期，请重新登录")
      router.push("/login")
    }
    return Promise.reject(error)
  }
)
export default request
